<template>
  <div id="TopicChecked">
    <el-breadcrumb
      separator="/"
      style="padding-left: 10px; padding-bottom: 10px; font-size: 12px"
    >
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动上传</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" shadow="hover">
      <el-form
        :inline="true"
        :model="queryMap"
        size="small"
        class="demo-form-inline"
      >
        <el-form-item label="活动名称">
          <el-input
            v-model="queryMap.topicName"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="活动类型">
          <el-select
            v-model="queryMap.topicTypeId"
            placeholder="请选择活动类型"
            clearable
          >
            <el-option
              v-for="item in topicTypes"
              :key="item.topicTypeId"
              :label="item.topicTypeName"
              :value="item.topicTypeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否必选">
          <el-select
            v-model="queryMap.compulsory"
            placeholder="请选择"
            clearable
          >
            <el-option :key="true" label="必选" :value="true"></el-option>
            <el-option :key="false" label="可选" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传类型">
          <el-select
            v-model="queryMap.uploadType"
            placeholder="请选择上传类型"
            clearable
          >
            <el-option :key="true" label="管理员上传" :value="true"></el-option>
            <el-option :key="false" label="自行上传" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动划分">
          <el-select
            v-model="queryMap.cover"
            placeholder="请选择活动划分"
            clearable
          >
            <el-option :key="false" label="班级活动" :value="false"></el-option>
            <el-option
              :key="true"
              label="院级/校级活动"
              :value="true"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="search"
            type="primary"
            icon="el-icon-search"
            :loading="loading"
            round
            >查询</el-button
          >
          <el-button
            type="success"
            icon="el-icon-plus"
            @click="saveOperate"
            round
            >添加</el-button
          >
        </el-form-item>
        <el-form-item>
          <!--limit:最大上传数，on-exceed：超过最大上传数量时的操作  -->
          <el-upload
            class="upload-demo"
            icon="el-icon-upload2"
            action=""
            :on-change="handleChange"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :limit="limitUpload"
            accept="application/vnd.openxmlformats-    
        officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
            :auto-upload="false"
          >
            <el-tooltip
              class="item"
              effect="dark"
              content="分数导入入口"
              placement="top-start"
            >
              <el-button
                size="small"
                type="warning"
                round
                icon="el-icon-upload2"
                >分数导入</el-button
              >
            </el-tooltip>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-tooltip
            class="item"
            effect="dark"
            content="外部分数导入模板"
            placement="top-start"
          >
            <el-link
              type="primary"
              icon="el-icon-download"
              round
              href="/outside.xls"
              >模板导出</el-link
            ></el-tooltip
          >
        </el-form-item>
      </el-form>
      <template>
        <el-table
          :data="topicVOS"
          border
          stripe
          size="small"
          style="width: 100%; margin-top: 5px"
        >
          <el-table-column
            prop="topicName"
            label="活动名称"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="masterName"
            label="活动负责人"
            align="center"
          ></el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center"
            ><template slot-scope="scope">{{
              scope.row.createTime | dateFormat
            }}</template></el-table-column
          >
          <el-table-column
            prop="expirationTime"
            label="过期时间"
            align="center"
          >
            <template slot-scope="scope">{{
              scope.row.expirationTime | dateFormat
            }}</template></el-table-column
          >
          <el-table-column
            prop="scoreRange"
            label="分数范围"
            align="center"
          ></el-table-column>
          <el-table-column label="是否必选" width="200" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.compulsory"
                active-text="必选"
                inactive-text="可选"
                disabled
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.status == 0" style="color: #ff4949"
                >审核不通过</span
              >
              <span v-if="scope.row.status == 1">已提交</span>
              <span
                v-if="scope.row.status == 2 || scope.row.status == null"
                style="color: #13ce66"
                >审核已经通过</span
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-popconfirm
                confirmButtonText="审核"
                cancelButtonText="撤回"
                icon="el-icon-info"
                iconColor="red"
                title="确定您当前的操作吗？"
                @onConfirm="approvedTopic(scope.row.topicId, 2)"
                @onCancel="approvedTopic(scope.row.topicId, 0)"
              >
                <el-button
                  slot="reference"
                  icon="el-icon-thumb"
                  type="text"
                  size="mini"
                  :disabled="scope.row.status == null && scope.row.score == 2"
                  >审核</el-button
                >
              </el-popconfirm>
              <el-button
                type="text"
                icon="el-icon-edit"
                size="mini"
                :loading="loading"
                @click="getCurrentTopic(scope.row.topicId)"
                >编辑</el-button
              >
              <el-button
                type="text"
                icon="el-icon-delete"
                size="mini"
                :loading="loading"
                @click="delTopicByTopicId(scope.row.topicId)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 分页 -->
      <el-pagination
        style="margin-top: 10px"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.queryMap.page"
        :page-sizes="[10, 50, 100]"
        :page-size="this.queryMap.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <el-drawer :visible.sync="show" size="20%" direction="rtl">
        <template slot="title" align="center"><div>活动详情信息</div></template>
        <el-form
          :model="currentTopic"
          align="center"
          ref="topicRulesRef"
          :rules="topicRules"
          style="margin-left: 10px"
        >
          <el-form-item
            label="活动名称"
            label-width="80px"
            :rules="[
              {
                required: true,
                message: '活动名称不能为空',
                trigger: 'blur',
              },
            ]"
            prop="topicName"
          >
            <el-input
              v-model="currentTopic.topicName"
              autocomplete="off"
              style="width: 220px"
              placeholder="必须少于25个字"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="分数范围"
            label-width="80px"
            :rules="[
              {
                required: true,
                message: '分数范围不能为空',
                trigger: 'blur',
              },
            ]"
            prop="scoreRange"
          >
            <el-input
              v-model="currentTopic.scoreRange"
              autocomplete="off"
              style="width: 220px"
              placeholder="格式：数字-数字"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="学分"
            label-width="80px"
            :rules="[
              {
                required: true,
                message: '学分不能为空',
                trigger: 'blur',
              },
            ]"
            prop="supportUploadScore"
          >
            <el-input-number
              v-model="currentTopic.supportUploadScore"
              style="width: 220px"
              :step="0.1"
              :min="0.1"
              :max="10"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="创建时间" label-width="80px">
            <el-date-picker
              v-model="currentTopic.createTime"
              type="datetime"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="过期时间"
            label-width="80px"
            :rules="[
              {
                required: true,
                message: '过期时间不能为空',
                trigger: 'blur',
              },
            ]"
            prop="expirationTime"
          >
            <el-date-picker
              v-model="currentTopic.expirationTime"
              type="datetime"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="活动类型"
            label-width="80px"
            :rules="[
              {
                required: true,
                message: '活动类型不能为空',
                trigger: 'blur',
              },
            ]"
            prop="topicType"
          >
            <el-select
              v-model="currentTopic.topicType"
              placeholder="请选择活动类型"
            >
              <el-option
                v-for="item in topicTypes"
                :key="item.topicTypeId"
                :label="item.topicTypeName"
                :value="item.topicTypeId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="是否必选"
            label-width="80px"
            :rules="[
              {
                required: true,
                message: '此项不能为空',
                trigger: 'blur',
              },
            ]"
            prop="compulsory"
          >
            <el-select v-model="currentTopic.compulsory" placeholder="请选择">
              <el-option :key="true" label="必选" :value="true"></el-option>
              <el-option :key="false" label="可选" :value="false"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上传类型" label-width="80px" prop="uploadType">
            <el-select
              v-model="currentTopic.uploadType"
              placeholder="请选择上传类型"
              disabled
            >
              <el-option
                :key="true"
                label="管理员上传"
                :value="true"
              ></el-option>
              <el-option
                :key="false"
                label="自行上传"
                :value="false"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="活动划分"
            label-width="80px"
            :rules="[
              {
                required: true,
                message: '活动划分不能为空',
                trigger: 'blur',
              },
            ]"
            prop="cover"
          >
            <el-select
              v-model="currentTopic.cover"
              placeholder="请选择活动划分"
              clearable
            >
              <el-option
                :key="false"
                label="班级活动"
                :value="false"
              ></el-option>
              <el-option
                :key="true"
                label="院级/校级活动"
                :value="true"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="人数上限"
            label-width="80px"
            :rules="[
              {
                required: true,
                message: '人数上限不能为空',
                trigger: 'blur',
              },
            ]"
            prop="limited"
          >
            <el-input-number
              v-model="currentTopic.limited"
              style="width: 220px"
              :step="10"
              :min="1"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="备注" label-width="80px">
            <el-input
              type="textarea"
              placeholder="请输入内容"
              v-model="currentTopic.comment"
              maxlength="30"
              show-word-limit
              style="width: 220px"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-footer" align="center">
          <el-button
            type="primary"
            :loading="loading"
            @click="updateCurrentTopic(currentTopic.topicId)"
            >确 定</el-button
          >
          <el-button @click="show = false">取 消</el-button>
        </div>
      </el-drawer>
    </el-card>
  </div>
</template>
<script>
import {
  queryTopicsByPage,
  queryTopicTypes,
  queryCurrentTopicByTopicId,
  editCurrentTopic,
  saveCurrentTopic,
  delTopic,
  outerPortScore,
  approved,
} from "api/api";
import { mapState } from "vuex";
export default {
  data() {
    return {
      queryMap: { page: 1, size: 10 },
      total: 0,
      topicTypes: [],
      topicVOS: [],
      loading: false,
      show: false,
      currentTopic: {},
      topicRules: {},
      limitUpload: 2,
    };
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  methods: {
    //改变页码
    handleSizeChange(newSize) {
      this.queryMap.size = newSize;
      this.getTopicsByPage();
    },
    //翻页
    handleCurrentChange(current) {
      this.queryMap.page = current;
      this.getTopicsByPage();
    },
    //获取活动列表
    getTopicsByPage() {
      queryTopicsByPage(this.userInfo.sessionId, this.queryMap).then((res) => {
        if (!res.flag) {
          this.$message.error(res.message);
        } else {
          this.total = res.data.total;
          this.topicVOS = res.data.rows;
        }
      });
    },
    //获取活动类型列表
    getTopicTypes() {
      queryTopicTypes(this.userInfo.sessionId).then((res) => {
        if (!res.flag) {
          this.$message.error(res.message);
        } else {
          this.topicTypes = res.data;
        }
      });
    },
    //查询
    async search() {
      this.loading = true;
      //初始化操作
      this.total = 0;
      this.topicVOS = [];
      await queryTopicsByPage(this.userInfo.sessionId, this.queryMap).then(
        (res) => {
          if (!res.flag) {
            this.$message.error(res.message);
            this.loading = false;
          } else {
            this.total = res.data.total;
            this.topicVOS = res.data.rows;
            this.loading = false;
          }
        }
      );
    },
    //获取当前活动详情
    getCurrentTopic(topicId) {
      queryCurrentTopicByTopicId(this.userInfo.sessionId, topicId).then(
        (res) => {
          this.loading = true;
          this.show = true;
          if (!res.flag) {
            this.$message.error(res.message);
            this.loading = false;
          } else {
            this.currentTopic = res.data;
            this.loading = false;
          }
        }
      );
    },
    //新增操作
    saveOperate() {
      this.show = true;
      //初始化才操作
      this.currentTopic = {};
    },
    //新增或编辑活动详情信息
    updateCurrentTopic(topicId) {
      this.loading = true;
      this.$refs.topicRulesRef.validate((valid) => {
        if (!valid) {
          this.loading = false;
          return;
        } else {
          if (topicId == null) {
            //新增操作
            this.currentTopic.uploadType = true;
            saveCurrentTopic(this.userInfo.sessionId, this.currentTopic)
              .then((res) => {
                if (!res.flag) {
                  this.$message.error(res.message);
                  this.loading = false;
                } else {
                  this.$message({
                    type: "success",
                    message: "新增成功！",
                  });
                  this.loading = false;
                  this.show = false;
                  //进行刷新操作
                  this.getTopicsByPage();
                }
              })
              .catch((err) => {
                this.loading = false;
                this.$message.error("编辑失败，请联系管理员!");
              });
          } else {
            //编辑操作
            editCurrentTopic(this.userInfo.sessionId, this.currentTopic)
              .then((res) => {
                if (!res.flag) {
                  this.$message.error(res.message);
                  this.loading = false;
                } else {
                  this.$message({
                    type: "success",
                    message: "更新成功！",
                  });
                  this.loading = false;
                  this.show = false;
                  //进行刷新操作
                  this.getTopicsByPage();
                }
              })
              .catch((err) => {
                this.loading = false;
                this.$message.error("编辑失败，请联系管理员!");
              });
          }
        }
      });
    },
    //根据活动id删除活动
    async delTopicByTopicId(topicId) {
      var res = await this.$confirm(
        "此操作将删除该活动记录，你将会减少相应的分数，是否继续",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消操作！",
        });
      });
      if (res == "confirm") {
        this.loading = true;
        await delTopic(topicId)
          .then((res) => {
            if (!res.flag) {
              this.$message.error(res.message);
              this.loading = false;
            } else {
              this.$message({
                type: "success",
                message: "删除成功！",
              });
              this.loading = false;
              this.getTopicsByPage();
            }
          })
          .catch((err) => {
            this.loading = false;
          });
      }
    },
    async handleChange(file, fileList) {
      this.fileTemp = file.raw;
      if (this.fileTemp) {
        if (
          this.fileTemp.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          this.fileTemp.type == "application/vnd.ms-excel"
        ) {
          await this.importStuList(this.fileTemp);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请删除后重新上传！",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件！",
        });
      }
    },
    //超出最大上传文件数量时的处理方法
    async handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    //移除文件的操作方法
    async handleRemove(file, fileList) {
      this.fileTemp = null;
    },
    //数据清洗
    async importStuList(obj) {
      let _this = this;
      let inputDOM = this.$refs.inputer;
      // 通过DOM取文件数据
      this.file = event.currentTarget.files[0];
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = (e) => {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          //此处引入，用于解析excel
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64",
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary",
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
          //outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
          //此处可对数据进行处理
          let arr = [];
          outdata.map((v) => {
            let obj = {};
            obj.stuNum = v["学号"];
            obj.stuName = v["姓名"];
            obj.className = v["班级"];
            obj.topicTypeName = v["活动类型"];
            obj.topicName = v["活动名称"];
            obj.score = v["学分"];
            arr.push(obj);
          });
          _this.importData(arr);
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    //数据导入
    importData(data) {
      console.log(data);
      this.loading = true;
      outerPortScore(data).then((res) => {
        if (!res.flag) {
          this.$message.error(res.message + ":" + res.data);
          this.loading = false;
        } else {
          this.$message({
            type: "success",
            message: "数据导入成功！",
          });
          this.getTopicsByPage();
          this.loading = false;
        }
      });
    },
    approvedTopic(topicId, status) {
      approved(topicId, status).then((res) => {
        if (!res.flag) {
          this.$message.error(res.message + ":" + res.data);
          this.loading = false;
        } else {
          this.$message({
            type: "success",
            message: "审核成功",
          });
          this.getTopicsByPage();
          this.loading = false;
        }
      });
    },
  },
  mounted() {
    this.getTopicsByPage();
    this.getTopicTypes();
  },
};
</script>